package org.zjvis.datascience.service.audit;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.zjvis.datascience.common.dto.AuditDTO;
import org.zjvis.datascience.common.dto.AuditQueryDTO;
import org.zjvis.datascience.service.mapper.AuditMapper;

import java.util.List;

/**
 * @description 接口审计 Service
 * @date 2021-01-08
 */
@Slf4j
@Service
public class AuditService {

    @Autowired
    private AuditMapper auditMapper;

    /**
     * 分页查询Audit信息
     *
     * @param dto
     * @return
     */
    public PageInfo<AuditDTO> queryAuditByPage(AuditQueryDTO dto) {
        log.info("queryAuditByPage, query={}", dto);
        if (dto.getPageSize() == null || dto.getPageSize() == 0) {
            dto.setPageSize(15); //默认每页显示15条记录
        }
        if (dto.getCurPage() == null || dto.getCurPage() <= 0) {
            dto.setCurPage(1); //默认显示第一页
        }
        dto.setPageStart((dto.getCurPage() - 1) * dto.getPageSize());
        PageHelper.startPage(dto.getCurPage(), dto.getPageSize());
        List<AuditDTO> auditDTOS = auditMapper.selectPage(dto);
        return new PageInfo<>(auditDTOS);
    }

    /**
     * 操作数据库批量插入数据
     *
     * @param auditDTOS
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int batchInsert(List<AuditDTO> auditDTOS) {
        if (auditDTOS == null || auditDTOS.isEmpty()) {
            return 0;
        }
        int result = auditDTOS.size();
        try {
            auditMapper.insertBatch(auditDTOS);
        } catch (Exception e) {
            result = 0;
            log.error("batch insert to db error!", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    /**
     * 供controller调用，插入审计数据
     *
     * @param audit
     * @return
     */
    public boolean addAuditInfo(AuditDTO audit) {
        return ScheduledService.offer(audit);
    }

}
